'use strict';
// Copyright 2014 Blueant Inc. All Rights Reserved.

/**
 * @fileoverview 建筑
 * @author sundbcn@gmail.com (sun debing)
 */

var _ = require('lodash');
var async = require('async');
var soldierService = require('./soldierService.js');
var atkData = require('../libs/war/atkData.js');
var soldierModel = require('../models/soldierModel.js');
var Code = require('../consts/code');
var constantUtil = require('../util/constantUtil.js');

/**
 * 计算士兵最高战力
 * @param  {[type]}   soldier_model      [description]
 * @return {[type]}             [description]
 */
exports.getMaxSoldierPower = function (soldier_list) {
    var power_list = [];

    _.each(soldier_list, function (si) {
        var curr_power = soldierService.getSoldierPower(si.soldier_type, si.lv, si.star, si.talent);
        power_list.push(curr_power);
    });

    var sorted_list = _.orderBy(power_list, null, ['desc']);
    // 截取战力最高的5个
    sorted_list = _.slice(sorted_list, 0, 5);
    var max_power = 0;
    _.forEach(sorted_list, function (val) {
        max_power += val;
    });

    return Math.ceil(max_power);
};

/**
 * 随机生成远征对手列表
 */
exports.getExpeditionRivalList = function (player_manager, callback) {
    var self = this;
    var rival_count = 6;
    var rival_range_count = 60;
    var role_id = player_manager.getRoleId();

    var rival_list = [];
    async.waterfall(
        [
            function (cb) {
                player_manager.getModel(['soldier', 'accrued'], cb);
            },
            function (cb) {
                var soldier_model = player_manager.soldier;
                var max_power = self.getMaxSoldierPower(soldier_model.soldier_list);
                var expedition_power_ratio = constantUtil.value('expedition_power_ratio');
                var find_power = max_power * expedition_power_ratio / 100;
                soldierModel.findByPower(role_id, find_power, rival_range_count, function (err, list) {
                    if (list.length <= rival_count) {
                        _.forEach(list, function (item) {
                            rival_list.push(item.role_id);
                        });
                    } else {
                        rival_list = _randRivalList(list, rival_count);
                    }
                    cb();
                });
            }
        ],
        function (err) {
            if (!!err) {
                return callback(null, {
                    code: Code.FAIL
                });
            }
            callback(null, rival_list);
        }
    );
};

/**
 * 生成远征随机角色ID列表
 */
var _randRivalList = function (list, rival_count) {
    var rival_list = [];
    var step = Math.ceil(list.length / rival_count);
    var start_idx = 0;
    var max_idx = list.length - 1;
    for (var i = 0; i < rival_count; i++) {
        var rnd_idx = _.random(start_idx, start_idx + step - 1);
        if (rnd_idx > max_idx) {
            rnd_idx = max_idx;
        }
        rival_list.push(list[rnd_idx].role_id);
        start_idx += step;
    }

    return rival_list;
};

/**
 * 重置玩家远征数据
 */
exports.reset = function (player_manager, callback) {
    var self = this;
    async.waterfall(
        [
            function (cb) {
                player_manager.refreshData(cb);
            },
            function (cb) {
                player_manager.getModel(['expedition', 'arena', 'accrued'], cb);
            },
            function (cb) {
                self.getExpeditionRivalList(player_manager, function (err, rival_id_list) {
                    if (!!err) {
                        return callback(err);
                    }

                    _getExpdRivalInfo(rival_id_list, cb);
                });
            },
            function (rival_info_list, cb) {
                var expedition_model = player_manager.expedition;
                var arena_model = player_manager.arena;
                expedition_model.setRivalList(rival_info_list);

                expedition_model.box_id = 0;
                expedition_model.pass_id = 0;
                expedition_model.battle_tm = 0;
                expedition_model.soldier_hp_list = [];
                expedition_model.setSoldierList(arena_model.att_soldier_list);
                expedition_model.remain_times--;

                player_manager.save(cb);
            }
        ],
        function (err) {
            callback(err);
        }
    );
};

/**
 * 取出对手详细信息
 */
var _getExpdRivalInfo = function (rival_id_list, callback) {
    var rival_info_list = [];
    async.eachSeries(rival_id_list, function (rival_id, cb) {
        atkData.getDataForArena(rival_id, 1, function (err, rival_info) {
            rival_info.role_id = rival_id;
            _.forEach(rival_info.soldier_list, function (item) {
                // 设置当前血量为满血
                if (!!item) {
                    item.attr.curr_hp = item.attr.hp;
                }
            });

            rival_info_list.push(rival_info);
            cb();
        });

    }, function (err) {
        callback(err, rival_info_list);
    });
};
